package com.bbs.user.impl;

import com.bbs.utils.SystemEnum;
import com.bbs.utils.SystemResult;
import com.bbs.example.UserExample;
import com.bbs.model.UserParams;
import com.bbs.user.User;
import com.bbs.user.UserService;
import com.bbs.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.xml.rpc.ServiceException;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Value("${upload.url}")
    private String url;

    @Override
    public SystemResult userList(UserParams userParams) {
        List<User> users = userMapper.selectUserList(userParams);
        UserExample userExample = new UserExample();
        List<User> userList = userMapper.selectByExample(userExample);
        return new SystemResult(SystemEnum.RESULT_OK.getCode(),SystemEnum.RESULT_OK.getMessage(),users,userList.size());
    }

    @Override
    public SystemResult addOrUpdate(User user) {
        if (user.getId() != null){
            user.setUpdateDate(new Date());
            userMapper.updateByPrimaryKeySelective(user);
        } else {
            if (StringUtils.isBlank(user.getPassword()) ){
                user.setPassword("123456");
            }
            user.setAddDate(new Date());
            user.setState(1);
            userMapper.insertSelective(user);
        }
        return new SystemResult().RESPONSE_RESULT;
    }

    @Override
    public SystemResult del(Integer id) {
        userMapper.deleteByPrimaryKey(id);
        return new SystemResult().RESPONSE_RESULT;
    }

    @Override
    public SystemResult checkUser(String userName) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserNameEqualTo(userName);
        List<User> users = userMapper.selectByExample(userExample);
        return new SystemResult(SystemEnum.RESULT_OK.getCode(),SystemEnum.RESULT_OK.getMessage(),users,users.size());
    }

    @Override
    public User selectUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public SystemResult upload(HttpServletRequest request) {
        List<MultipartFile> files = new ArrayList<>();
        if (((MultipartHttpServletRequest) request).getFiles("file").size() != 0) {
            files = ((MultipartHttpServletRequest) request)
                    .getFiles("file");
        }
        if (files.isEmpty()){
            return new SystemResult(SystemEnum.RESULT_ERROR.getCode(),"文件不能为空");
        } else {
            MultipartFile file = files.get(0);
            if (file.getSize() != 0) {
//                SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
//                String dateString = format.format(new Date());
                int randomNumber = (int) (Math.random() * 90 + 10);
                StringBuilder picPath = new StringBuilder(url);
                picPath.append('/');
//                picPath.append(dateString);
//                picPath.append('_');
//                picPath.append(randomNumber);
//                picPath.append('_');
                String str = file.getOriginalFilename();
                str = str.replaceAll(" ", "");
                if (str.indexOf("\\") != -1) {
                    int index = str.lastIndexOf("\\");
                    str = str.substring(index + 1);
                }
                picPath.append(str);

                try {
                    //上传文件功能
                    File newFile = new File(picPath.toString());
                    if (!newFile.getParentFile().exists()) {
                        if (!newFile.getParentFile().mkdirs()) {
                            throw new ServiceException("创建路径失败");
                        }
                    }
                    //上传文件功能
                    file.transferTo(newFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                return new SystemResult(SystemEnum.RESULT_ERROR.getCode(), "上传失败，文件不能为空");
            }
        }
        return new SystemResult(SystemEnum.RESULT_OK.getCode(), "上传成功");
    }
}
